package com.org.manhu.chargehelper.service;

import java.text.DecimalFormat;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.tools.ApkInfoUtils;
import com.org.manhu.chargehelper.tools.AppManager;
import com.org.manhu.chargehelper.tools.Sever;
import com.org.manhu.chargehelper.tools.StringUtils;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

/**
 * @文件名：Service.java
 * @包名：com.example.textlog
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月4日 下午7:32:13
 *
 * @描述：
 */
@SuppressLint("HandlerLeak")
public class ServerService extends Service {

	private Sever sever;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 1){//获取到数据
				Intent intent = new Intent(Constant.ACTION_ACCEPT_DATA);
				intent.putExtra("data", msg.obj.toString());
				ChargeApplication.mApplicationContext.sendBroadcast(intent);
			}else if(msg.what == 2){//文件已经推送到手机
				
			}
		};
	};

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		sever = Sever.getInstance();
		if (!sever.isAlive()) {// 如果线程已启动则不在执行该方法
			sever.start();
		}
		sever.setHandler(mHandler);
		registerReceiver(mBatteryInfoReceiver, new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED));
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}
	
	/**
	 * @描述：
	 */
	private void ondestory() {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.setAction("com.org.manuhu.chargehelper.RESTART_SERVER_RECEIVER");
		sendBroadcast(intent);
	}

	private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {

				int level = intent.getIntExtra("level", 0);
				int scale = intent.getIntExtra("scale", 100);

				float chargeLevel = (float) (level / (scale * 1.00));
				DecimalFormat df = new DecimalFormat("0.00");

				Sever.getInstance().sendMessageToClient(
						StringUtils.chargeJson(df.format(chargeLevel)));
			}
		}
	};

}
